package cn.edu.web;

import cn.edu.pojo.Student;
import cn.edu.service.StudentService;
import cn.edu.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends BaseServlet {

    StudentService studentService = new StudentServiceImpl();

        protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String save = req.getParameter("save");
        Student student = studentService.queryStudentBySnoAndPassword(username, password);
        //不为null表示用户名密码正确
        if (student!=null){
            //save==1表示记住密码
            if("1".equals(save)){
                Cookie userCookie = new Cookie("username",username);
                Cookie passwordCookie = new Cookie("password",password);
                userCookie.setMaxAge(60*60*24*7);
                passwordCookie.setMaxAge(60*60*24*7);
                resp.addCookie(userCookie);
                resp.addCookie(passwordCookie);
            }
            req.getSession().setAttribute("user",student);
            req.getRequestDispatcher("/bookServlet?action=allBook").forward(req,resp);
        }else {
            req.setAttribute("msg","用户名或者密码错误");
            req.setAttribute("username",username);
            req.setAttribute("password",password);
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
